//
//  YWAttendanceRecordDetailTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/8/23.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWAttendanceRecordDetailTableViewController.h"
#import "YWObserverTableViewController.h"
#import "YWSelectAtUserTableViewController.h"
#import "UIColor+CustomColors.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YWConst.h"
#import "YWMacro.h"
#import "Masonry.h"
#import "UIView+Extension.h"

//#import "YWImageView.h"
#import "YWPhotoView.h"
#import "MBProgressHUD.h"
#import "NSDate+YYAdd.h"
#import "UIImage+Extension.h"
#import "WMHttpTool.h"
#import "YWAttendanceManager.h"
#import "YWAttendanceRecord.h"
#import "YWCommonTool.h"
#import "YWKeepWatchMissionManager.h"
#import "YWBuildingManager.h"
#import "YWEquipmentManager.h"
#import "YWReplyManager.h"
#import "YWLoginTool.h"

#import "YWWriteNoteCell.h"
#import "YWMeterReadingDetailRecordCell.h"
#import "YWObserveTableViewCell.h"
#import "YWNewReplyTableViewCell.h"

@interface YWAttendanceRecordDetailTableViewController ()<YWWriteNoteCellDelegate,UITextFieldDelegate,YWSelectAtUserTableViewDelegate>
{
    NSString *replyContent;
}
@property (nonatomic, strong) NSMutableArray *dateSource;
@property (nonatomic, strong) NSString *note;
/** 图片容器 */
@property (nonatomic, strong) UIView* pictureView;
//@property (nonatomic, strong) UIView* footView;
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) NSArray *replyArray;//评论数组
@property (nonatomic, strong) UIView *replyView;//回复栏
@property (nonatomic, strong) YWHandler *atUser;
@property (nonatomic, strong) UIButton * selectButton;
@property (nonatomic, strong) UITextField * textField;
@property (nonatomic, strong) UIView * line2;
@end

@implementation YWAttendanceRecordDetailTableViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"recordsDetail", nil);//@"记录详情";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    [self.tableView registerClass:[YWMeterReadingDetailRecordCell class] forCellReuseIdentifier:YWMeterReadingDetailRecordCellIdentifier];
    
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWObserveTableViewCell class] forCellReuseIdentifier:YWObserveTableViewCellIdentifier];
    [self.tableView registerClass:[YWNewReplyTableViewCell class] forCellReuseIdentifier:YWNewReplyTableViewCellIdetifer];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
//    self.tableView.tableFooterView = self.footView;
    [self.navigationController.view addSubview:self.replyView];
    self.tableView.estimatedRowHeight = 90.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    if (self.attendanceRecord.arriveTime == 0) {
        [self requestAttendanceRecordDetail];//当从评论进来时请求
    }
}

- (void)requestAttendanceRecordDetail{
    YWWeakSelf(weakSelf);
    [[YWAttendanceManager shareManager] getAttendanceRecordWithAttendanceRecordId:self.attendanceRecord.recordId WithComplete:^(YWAttendanceRecord *record) {
        if (record) {
            weakSelf.attendanceRecord = record;
            weakSelf.attendanceRecord.uploadStatus = YWAttendanceUploadStatusSucceed;
            weakSelf.dateSource = nil;
            weakSelf.replyArray = nil;
            [weakSelf.tableView reloadData];
        }
    }];
}

- (void)setAttendanceRecord:(YWAttendanceRecord *)attendanceRecord{
    _attendanceRecord = attendanceRecord;
    YWHandler *attendanceUser = [[YWHandler alloc] init];
    attendanceUser.userName = [YWLoginTool loginUser].userName;
    attendanceUser.uniqueId = [YWLoginTool loginUser].uniqueId;
    _attendanceRecord.user = attendanceUser;
}

- (NSArray *)replyArray{
    if (!_replyArray) {
        NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:[self.attendanceRecord.recordId integerValue] andRelationType:YWReplyRelationTypeAttendance];
        _replyArray = commentArray;
    }
    return _replyArray;
}

- (NSMutableArray*)dateSource
{
    if (!_dateSource) {
        _dateSource = [NSMutableArray array];
        [_dateSource addObject:[self dateLabelString]];
        [_dateSource addObject:[self executor]];
        [_dateSource addObject:[self arriveLabelString]];
        [_dateSource addObject:[self GPSLabelString]];
        [_dateSource addObject:[self locationText]];
        [_dateSource addObject:[self arriveNoteLabelString]];
        if (self.attendanceRecord.uploadStatus == YWAttendanceUploadStatusFailure) {
            [_dateSource addObject:[self uploadStatusFailureLabelString]];
        }
        if (self.attendanceRecord.uploadStatus == YWAttendanceUploadStatusChangeTime) {
            [_dateSource addObject:[self uploadStatusChangeTimeLabelString]];
        }
        if (self.attendanceRecord.uploadStatus == YWAttendanceUploadStatusUploading) {
            [_dateSource addObject:[self uploadStatusUploadingLabelString]];
        }
    }
    return _dateSource;
}

- (NSString*)executor{
    NSString *handler = self.attendanceRecord.user.userName;
    NSString* type = self.attendanceRecord.type == YWAttendanceTypeArrive ? NSLocalizedString(@"arrive", nil) : NSLocalizedString(@"leave", nil);
    return [NSString stringWithFormat:@"%@人: %@",type,handler.length?handler:NSLocalizedString(@"none", nil)];
}


- (NSString*)dateLabelString
{
    NSString* dateLabelString = [NSString stringWithFormat:@"%ld年%@", (long)(self.attendanceRecord.yearMonthDay / 10000), self.attendanceRecord.dateShow];
    return dateLabelString;
}

- (NSString*)arriveLabelString
{
//    NSDate* arriveDate = [NSDate dateWithTimeIntervalSince1970:self.attendanceRecord.arriveTime/1000];
    NSString *timeString = [YWCommonTool showTime:self.attendanceRecord.arriveTime/1000 andFormatter:KTimeFormatShortTimeDate];
    NSString* type = self.attendanceRecord.type == YWAttendanceTypeArrive ? NSLocalizedString(@"arrive", nil) : NSLocalizedString(@"leave", nil);
    NSString* arriveLabelString = [NSString stringWithFormat:@"%@%@：%@", type,NSLocalizedString(@"time", nil), timeString];
    return arriveLabelString;
}

- (NSString*)GPSLabelString{
    NSString *GPSStr = self.attendanceRecord.locationText.length>0?self.attendanceRecord.locationText:NSLocalizedString(@"none", nil);
    NSString *GPSlocationText = [NSString stringWithFormat:@"GPS位置：%@",GPSStr];
    return GPSlocationText;
}

- (NSString*)locationText{
    NSInteger locationId = 0;
    if (self.attendanceRecord.locationId) {
        locationId = self.attendanceRecord.locationId;
    }else if (self.attendanceRecord.qrcodeId){
        locationId = self.attendanceRecord.qrcodeId?[[YWEquipmentManager shareManager]locationIdWithQrcodeId:self.attendanceRecord.qrcodeId]:0;
    }
    NSString *location = [[YWBuildingManager shareManager] areaLocationWithLocationId:locationId];
    NSString* type = self.attendanceRecord.type == YWAttendanceTypeArrive ? NSLocalizedString(@"arrive", nil) : NSLocalizedString(@"leave", nil);
    return [NSString stringWithFormat:@"%@%@: %@",type,NSLocalizedString(@"location", nil),location.length>0?location : NSLocalizedString(@"none", nil)];
}

- (NSString*)arriveNoteLabelString
{
    NSString* arriveNoteLabelString = [NSString stringWithFormat:@"%@：%@", NSLocalizedString(@"note", nil),self.attendanceRecord.arriveRemark.length ?self.attendanceRecord.arriveRemark: NSLocalizedString(@"none", nil)];
    return arriveNoteLabelString;
}

- (NSString*)uploadStatusFailureLabelString
{
    NSString* uploadStatusLabelString = [NSString stringWithFormat:NSLocalizedString(@"uploadFailedAndWaitToUploadAgain", nil)];
    return uploadStatusLabelString;
}

- (NSString*)uploadStatusChangeTimeLabelString{
    NSString* uploadStatusChangeTimeLabelString = [NSString stringWithFormat:NSLocalizedString(@"uploadFailedAndPleaseDontModifyYourMobileTime", nil)];
    return uploadStatusChangeTimeLabelString;
}
- (NSString*)uploadStatusUploadingLabelString
{
    NSString* uploadStatusUploadingLabelString = [NSString stringWithFormat:NSLocalizedString(@"uploadFailedAndWait", nil)];
    return uploadStatusUploadingLabelString;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.dateSource.count;
    }else {
        return self.replyArray.count == 0 ? 1 : self.replyArray.count+2;
    }
}

//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    if (indexPath.section == 0) {
//        return UITableViewAutomaticDimension;
////        [tableView fd_heightForCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMeterReadingDetailRecordCell *cell) {
////            cell.contentLabel.text = self.dateSource[indexPath.row];
////        }];
//    } else {
//        return 90;
//    }
//}

- (void)passNote:(NSString *)note{
    _note = note;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0) {
        YWMeterReadingDetailRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
        cell.contentLabel.text = self.dateSource[indexPath.row];
        return cell;
    }else{
        if (indexPath.row == 0) {
            YWObserveTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWObserveTableViewCellIdentifier];
            cell.attendanceRecord = self.attendanceRecord;
            return cell;
        }else{
            if (indexPath.row == 1) {
                YWMeterReadingDetailRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
                NSString *count;
                if (self.replyArray.count>0) {
                    count = [NSString stringWithFormat:@"(%ld)",(unsigned long)self.replyArray.count];
                }else{
                    count = @"";
                }
                NSString *replyText = [NSString stringWithFormat:@"%@%@:",NSLocalizedString(@"comment", nil),count];
                cell.contentLabel.text = replyText;
                cell.contentLabel.textColor = [UIColor customTextGrayColor];
                return cell;
            }
            YWNewReplyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNewReplyTableViewCellIdetifer];
            YWReply *reply = self.replyArray[indexPath.row-2];
            cell.reply = reply;
            return cell;
        }
    }
//    else {
//        YWWriteNoteCell* cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
//        cell.textViewPlaceHolder = @"如果签到/签退时间不对,您可以在此申诉";
//        cell.delegate = self;
//        return cell;
//    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0 ? 0.1 : 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return nil;
    }
    static NSString* HeaderIdentifier = @"YWAttendanceRecordDetailTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor whiteColor];
        //评论
        UILabel *replyLabel = [[UILabel alloc] init];
        replyLabel.textAlignment = NSTextAlignmentLeft;
        replyLabel.textColor = [UIColor customTextGrayColor];
        replyLabel.tag = 2006;
        replyLabel.font = KSmallContentFont;
        replyLabel.userInteractionEnabled = YES;
        [replyLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
        [headerView addSubview:replyLabel];
        
        UIImageView *replyImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"remind_replyIcon"]];
        replyImageView.tag = 2006;
        replyImageView.userInteractionEnabled = YES;
        [replyImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
        [headerView addSubview:replyImageView];
        
        [replyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(headerView);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(replyImageView.mas_top);
            make.left.mas_equalTo(replyImageView.mas_right).offset(8);
            make.right.mas_equalTo(headerView.mas_right).offset(-8);
            make.bottom.mas_equalTo(replyImageView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];
        //参与者
        UILabel *observerLabel = [[UILabel alloc] init];
        observerLabel.textAlignment = NSTextAlignmentLeft;
        observerLabel.textColor = [UIColor customTextGrayColor];
        observerLabel.tag = 2007;
        observerLabel.font = KSmallContentFont;
        observerLabel.userInteractionEnabled = YES;
        [observerLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
        [headerView addSubview:observerLabel];
        
        UIImageView *observerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_invite"]];
        observerView.tag = 2007;
        observerView.userInteractionEnabled = YES;
        [observerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
        [headerView addSubview:observerView];
        
        [observerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(headerView);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [observerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(observerView.mas_top);
            make.left.mas_equalTo(observerView.mas_right).offset(8);
            make.right.mas_equalTo(replyImageView.mas_left).offset(-8);
            make.bottom.mas_equalTo(observerView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];
        
        //分享
        UILabel *shareLabel = [[UILabel alloc] init];
        shareLabel.textAlignment = NSTextAlignmentLeft;
        shareLabel.textColor = [UIColor customTextGrayColor];
        shareLabel.tag = 2008;
        shareLabel.hidden = YES;
        shareLabel.font = KSmallContentFont;
        shareLabel.userInteractionEnabled = YES;
        [shareLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleShareLabelTapEvent:)]];
        [headerView addSubview:shareLabel];
        
        UIImageView *shareView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_share"]];
        shareView.tag = 2008;
        shareView.hidden = YES;
        shareView.userInteractionEnabled = YES;
        [shareView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleShareLabelTapEvent:)]];
        [headerView addSubview:shareView];
        [shareView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(headerView);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [shareLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(shareView.mas_top);
            make.left.mas_equalTo(shareView.mas_right).offset(8);
            make.right.mas_equalTo(observerView.mas_left).offset(-8);
            make.bottom.mas_equalTo(shareView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];
        UIView * lineView = [[UIView alloc] init];
        lineView.frame = CGRectMake(0, 29, SCREEN_WIDTH, 1);
        lineView.backgroundColor = [UIColor customLineColor];
        [headerView addSubview:lineView];
    }
    UILabel* label = [headerView viewWithTag:2006];
    label.text = NSLocalizedString(@"comment", nil);//@"评论";
    //参与者
    label = [headerView viewWithTag:2007];
    label.text = NSLocalizedString(@"invitation", nil);//@"邀请";
    //分享
//    label = [headerView viewWithTag:2008];
//    label.hidden = YES;
//    label.text = NSLocalizedString(@"share", nil);//@"分享";
    return headerView;
}

#pragma mark - 评论、邀请、分享等响应事件
- (void)handleReplyLabelTapEvent:(id)sender{
    [self.textField becomeFirstResponder];
}

- (void)handleObserverLabelTapEvent:(id)sender{
    YWObserverTableViewController *observerVC = [[YWObserverTableViewController alloc] init];
    observerVC.creaters =self.attendanceRecord.user?@[self.attendanceRecord.user]:nil;
    observerVC.observers = self.attendanceRecord.observers;
    observerVC.relationId = self.attendanceRecord.recordId;
    observerVC.type = YWReplyRelationTypeAttendance;
    [self.navigationController pushViewController:observerVC animated:YES];
}

- (void)handleShareLabelTapEvent:(id)sender{
    NSString *textToShare = NSLocalizedString(@"theContentNeedToShare", nil);//@"要分享的文本内容";
    //UIImage *imageToShare = [UIImage imageNamed:@"iosshare.jpg"];
    NSURL *urlToShare = [NSURL URLWithString:@"http://www.baidu.com"];
    
    NSArray *activityItems = @[textToShare, urlToShare];
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    NSMutableArray *excludedActivityTypes =  [NSMutableArray arrayWithArray:@[UIActivityTypeAirDrop, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypePrint, UIActivityTypeMail, UIActivityTypePostToTencentWeibo, UIActivityTypeSaveToCameraRoll, UIActivityTypeMessage, UIActivityTypePostToTwitter]];
    activityViewController.excludedActivityTypes = excludedActivityTypes;
    
    [self presentViewController:activityViewController animated:YES completion:nil];
    activityViewController.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
        //YWLog(@"%@  ----   %@", activityType, returnedItems);
        if (completed) {
            //YWLog(@"completed");
        }else{
            //YWLog(@"failed");
        }
    };
}

#pragma mark - tableview section foot view

- (UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return self.pictureView;
    }else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return self.pictureView.bounds.size.height;
    }else {
        return 0.01;
    }
}

- (UIView*)pictureView
{
    if (!_pictureView) {
        UIView* view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        _pictureView = view;
        CGFloat repairImageViewH = 0.1;
        NSArray* pictures = [[YWKeepWatchMissionManager shareManager] recordPictureWithRecordId:self.attendanceRecord.recordId recordType:YWPictureRecordTypeAttendance];
        if (pictures.count > 0) {
            YWPhotoView* imageV = [[YWPhotoView alloc] init];
            imageV.canAddPhoto = NO;
            imageV.photosArray = pictures;
            [imageV setFrame:CGRectMake(0, 10, imageV.frame.size.width, imageV.frame.size.height)];
            [_pictureView addSubview:imageV];
            repairImageViewH = imageV.frame.size.height + 20;
        }
        [_pictureView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, repairImageViewH)];
    }
    return _pictureView;
}
/*
- (UIView*)footView
{
    if (!_footView) {
        UIView* footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH + 15 * 2);
        footView.backgroundColor = [UIColor whiteColor];
        UIButton* appealButton = [UIButton buttonWithType:UIButtonTypeSystem];
        appealButton.frame = CGRectMake(10, 15, SCREEN_WIDTH - 10 * 2, kButtonH);
        [appealButton setBackgroundColor:[UIColor whiteColor]];
        [appealButton setTitle:@"申诉" forState:UIControlStateNormal];
        appealButton.titleLabel.font = kBoldTitleFont;
        [appealButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [appealButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [appealButton setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        appealButton.layer.borderColor = [UIColor customBlueColor].CGColor;
        appealButton.layer.borderWidth = 1.0;
        appealButton.layer.masksToBounds = YES;
        appealButton.layer.cornerRadius = 4.0;
        [appealButton addTarget:self action:@selector(handleappealButtonEvent) forControlEvents:UIControlEventTouchUpInside];
        [footView addSubview:appealButton];
        _footView = footView;
    }
    return _footView;
}

- (void)handleappealButtonEvent
{
    [self.view endEditing:YES];
    NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    YWWriteNoteCell* cell = (YWWriteNoteCell*)[self.tableView cellForRowAtIndexPath:indexPath];
    NSString* note = _note;
    if (note.length==0) {
        [YWCommonTool showTextHUDWithContent:@"请填写申诉内容"];
        return;
    }
    if (note.length>100) {
        [YWCommonTool showTextHUDWithContent:kTextNoteMax];
        return;
    }
    if ([YWCommonTool isContainsEmoji:note]) {
        [YWCommonTool showTextHUDWithContent:kTextCantContainEmoji];
        return;
    }
    if ([note isEqualToString:_attendanceRecord.arriveRemark]) {
        [YWCommonTool showTextHUDWithContent:@"您已经申诉过了"];
        return;
    }
    
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {return;}
    
    [self.HUD show:YES];
    NSDictionary* params = @{ @"attendanceRecordId" : self.attendanceRecord.recordId,
        @"note" : note };
    NSString *url = [YWCommonTool getAttendanceUrl];
    YWLog(@"签到申诉url:%@,params:%@",url,params);
    
    __block YWAttendanceRecord* blockAttendanceRecord = _attendanceRecord;
    [[WMHttpTool shareHttpTool] putWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        [self.HUD hide:YES];
        [YWCommonTool showTextHUDWithContent:kTextCommitSuccess];
        blockAttendanceRecord.arriveRemark = note;
        [[YWAttendanceManager shareManager] updateAttendanceRecordWithRecord:blockAttendanceRecord];
        cell.equipment = nil;
        _dateSource = nil;
        [self.tableView reloadData];
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        [self.HUD hide:YES];
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        [YWCommonTool showTextHUDWithContent:kTextAttendanceNoteFail];
    }];
}*/

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextAttendanceNoteStart, nil);
        hud.dimBackground = YES;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.view addSubview:hud];
    }
    return _HUD;
}

- (UIView *)replyView{
    if (!_replyView) {
        _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 46)];
        _replyView.backgroundColor = [UIColor whiteColor];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        line1.backgroundColor = [UIColor customLineColor];
        [_replyView addSubview:line1];
        _replyView.hidden = YES;
        [self setReplyViewLayout];
    }
    return _replyView;
}

- (void)setReplyViewLayout{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(40, 0, SCREEN_WIDTH-40-15, 40)];
    self.textField.placeholder = NSLocalizedString(@"reply", nil);//@"回复";
    self.textField.font = kContentFont;
    self.textField.returnKeyType = UIReturnKeySend;
    self.textField.delegate = self;
    self.line2 = [[UIView alloc] initWithFrame:CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1)];
    self.line2.backgroundColor = [UIColor customBlueColor];
    
    [_replyView addSubview:self.textField];
    [_replyView addSubview:self.line2];
    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectButton.frame = CGRectMake(0, 0, 40, 40);
    [self.selectButton addTarget:self action:@selector(handleSelectButtonToPeople:) forControlEvents:UIControlEventTouchUpInside];
    [_replyView addSubview:self.selectButton];
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

- (void)handleSelectButtonToPeople:(UIButton *)sende{
    YWSelectAtUserTableViewController * selectAtUserVC = [[YWSelectAtUserTableViewController alloc] init];
    selectAtUserVC.delegate = self;
    NSMutableArray *allUser = [NSMutableArray array];
    if (self.attendanceRecord.user) {
        [allUser addObject:self.attendanceRecord.user];
    }
    //observer
    [allUser addObjectsFromArray:self.attendanceRecord.observers];
    selectAtUserVC.allUserArray = allUser;
    [self.navigationController pushViewController:selectAtUserVC animated:YES];
}

- (void)selectAtUser:(YWHandler *)contact{
    if (contact) {
        self.atUser = contact;
        NSString * atButtonTitle = [NSString stringWithFormat:@"@%@",self.atUser.userName.length?self.atUser.userName:@""];
        CGSize size =[atButtonTitle sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGSize standernSize = [[NSString stringWithFormat:@"四个中文字"] sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGFloat width = size.width>standernSize.width ? standernSize.width : size.width;
        width = width + 6;//＋6是让前后有留白，不会紧贴屏幕
        self.selectButton.frame = CGRectMake(0, 0, width, kButtonH);
        self.textField.frame = CGRectMake(width, 0, SCREEN_WIDTH-width-15, kButtonH);
        self.line2.frame = CGRectMake(width, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
        
        self.selectButton.titleLabel.font = KTitleFont;
        [self.selectButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [self.selectButton setTitle:atButtonTitle forState:UIControlStateNormal];
    }else{
        [self whenAtUserIsNilReSetFrame];
    }
}

- (void)whenAtUserIsNilReSetFrame{
    self.atUser = nil;
    self.textField.text = nil;
    self.textField.frame = CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonH);
    self.line2.frame = CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"writeReplyContent", nil)];
        return NO;
    }else if (textField.text.length > 100){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replyContentLengthCannotMoreThan100", nil)];
        return NO;
    }else if ([YWCommonTool isContainsEmoji:textField.text]){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return NO;
    }
    replyContent = textField.text;
    NSString *url = [YWCommonTool postReplyUrl];
    [[YWReplyManager shareManager] commitReplys:[self createReply] url:url WithComplete:^(BOOL success) {
        if (success) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replySucceed", nil)];
            //回复成功后，要回复原样
            [self whenAtUserIsNilReSetFrame];
            _replyArray = nil;
            [self.tableView reloadData];
        }
    }];
    [textField endEditing:YES];
    return YES;
}

-(YWReply *)createReply{
    YWReply *reply = [[YWReply alloc]init];
    reply.replyId = 0;//提交成功后id会被服务端返回的id替换
    reply.relationId = [_attendanceRecord.recordId integerValue];
    reply.relationType = YWReplyRelationTypeAttendance;
    reply.content = replyContent;
    reply.atUser = _atUser;
    YWHandler *replier = [[YWHandler alloc] init];
    replier.uniqueId = [YWLoginTool loginUser].uniqueId;
    reply.replier = replier;
    reply.replyTime = [[NSDate date] timeIntervalSince1970]*1000;
    reply.isRead = YES;
    return reply;
}

- (void)addObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:self.attendanceRecord.observers];
        [tempArray addObject:handler];
        self.attendanceRecord.observers = [NSArray arrayWithArray:tempArray];
    }
}

- (void)deleteObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[self.attendanceRecord.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            NSMutableArray *tempArray = [NSMutableArray array];
            [tempArray addObjectsFromArray:self.attendanceRecord.observers];
            [tempArray removeObject:handler];
            self.attendanceRecord.observers = [NSArray arrayWithArray:tempArray];
        }
    }
}

#pragma mark ----- 有关键盘
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.replyView.hidden = YES;
    [self.textField endEditing:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.replyView.hidden = NO;
    [self setUpNotification];
}

- (void)setUpNotification{
    //    键盘show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //    键盘hide
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addObserver:) name:KPostMissionAddObserverNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteObserver:) name:KPostMissionDeleteObserverNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)info{
    //键盘高度
    CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    // 取得键盘的动画时间
    CGFloat duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 46 - kbHeight;
    }];
}

- (void)keyboardWillHide:(NSNotification *)info{
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT;
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.navigationController.view endEditing:YES];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
